<template>
  <div class="app-container calendar-list-container">
    <el-form :inline="true" size="default">
      <el-form-item label="AppName" lable-width="auto">
        <el-input v-model="listQuery.appname" @keyup.enter="handleFilter" 
          :prefix-icon="Search"
          style="width: 200px;" 
          placeholder="AppName" 
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="名称">
        <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="名称" v-model="listQuery.title" clearable>
      </el-input>
      </el-form-item>
      <el-form-item class="searchBtn">
        <el-button :icon="Search" class="filter-item" type="primary" @click="handleFilter">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item class="addText">
        <el-button :icon="Plus" class="filter-item" @click="executorCreate"
          :type="pageBoolean.addColor">
          {{ pageBoolean.addText }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref='list'
      :key='tableKey'
      :data="executorList"
      v-loading="listLoading"
      element-loading-text="数据加载中，请稍后"
      highlight-current-row
      fit
      select-on-indeterminate
      style="width: 100%">

      <!-- <el-table-column align="center" label="ID" min-width="30">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column align="center" label="AppName" min-width="100">
        <template #default="scope">
          <span class="link-type">{{scope.row.appname}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="名称" show-overflow-tooltip>
        <template #default="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="排序" min-width="40">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.order}}</span>
        </template>
      </el-table-column> -->

      <el-table-column min-width="60" align="center" label="注册方式" show-overflow-tooltip>
        <template #default="scope">
          <span v-html="formatRegDesc(scope.row.addressType)"></span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="OnLine机器地址" show-overflow-tooltip>
        <template #default="scope">
          <span v-html="formatAddressList(scope.row.addressList)"></span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="80">
        <template #default="scope">
          <el-button size="small" type="primary" @click="executorModify(scope.row)">编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="warnBeforeDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.currentPage"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.length"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog 
      v-model="dialogFormVisible"
      :title="dialogStatus=='create' ? '新增执行器' : '编辑执行器'" 
      center>
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="AppName" label-width="80px" prop="appname">
          <el-input v-model="form.appname" auto-complete="off" maxlength="180"
                    placeholder="请输入AppName"></el-input>
        </el-form-item>
        <el-form-item label="名称" label-width="80px" prop="title">
          <el-input v-model="form.title" auto-complete="off" maxlength="180"
                    placeholder="请输入名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="排序" label-width="80px" prop="order">
          <el-input-number v-model="form.order" :min="1" placeholder="请输入排列顺序"></el-input-number>
        </el-form-item> -->

        <el-form-item label="注册方式" prop="addressType">
          <el-select v-model="form.addressType" placeholder="请选择">
            <el-option v-for="item of addressTypeEnum"
                       :key="item.code"
                       :label="item.msg"
                       :value="item.code"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址列表" label-width="80px" prop="addressList">
          <el-input v-model="form.addressList" auto-complete="off" maxlength="180" type="textarea"
                    placeholder="请输入执行器地址，多个地址用逗号分隔"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {create, getGroupList, remove, update} from '@/api/scheduler'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

const addressTypeEnum = ref([
  {code: 0, msg: '自动注册'}, 
  {code: 1, msg: "手动注册"}
])

const dialogStatus = ref('create')
const dialogFormVisible = ref(false)
const userTypeCode = ref(null)
const userTypes = ref([
  {code: 0, msg: '超级管理员'}, 
  {code: 1, msg: '普通用户'}
])

const modifyData = ref('')
const form = ref({
  id: null,
  appname: '',
  title: '',
  addressType: null,
  addressList: ''
})

const rules = {
  appname: [{required: true, message: '请输入AppName', trigger: 'blur'}],
  title: [{required: true, message: '请输入执行器名称', trigger: 'blur'}],
  addressType: [{required: true, message: '请选择注册类型', trigger: 'blur'}]
}

const executorList = ref(null)
const total = ref(0)
const listLoading = ref(true)
const listQuery = ref({
  appname: '',
  title: '',
  start: 0,
  length: 10,
  currentPage: 1
})

const tableKey = ref(0)
const pageBoolean = ref({
  delColor: 'primary',
  delText: '批量删除',
  addColor: 'success',
  addText: '添加执行器'
})

const formRef = ref(null)

const fetchTableData = async () => {
  try {
    const res = await getGroupList(qs.stringify(listQuery.value))
    listLoading.value = false
    const { data, recordsTotal } = res
    executorList.value = data
    total.value = recordsTotal
    if (total.value === 0) {
      ElMessage({
        message: '执行器列表为空',
        type: 'warning'
      })
    }
  } catch (err) {
    console.log(err)
  }
}

const executorCreate = () => {
  form.value = {
    id: null,
    appname: '',
    title: '',
    addressType: null,
    addressList: ''
  }
  dialogFormVisible.value = true
  dialogStatus.value = 'create'
}

const addForm = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    const param = qs.stringify({
      'appname': form.value.appname,
      'title': form.value.title,
      'addressType': form.value.addressType,
      'addressList': form.value.addressList
    })
    
    try {
      const res = await create(param)
      if (res.code === 200) {
        dialogFormVisible.value = false
        ElMessage({
          message: "新增成功",
          type: 'success'
        })
        handleRefresh()
      } else {
        ElMessage(res.msg)
      }
      listLoading.value = false
    } catch (err) {
      console.log(err.message)
    }
  }
}

const executorModify = (row) => {
  dialogFormVisible.value = true
  dialogStatus.value = 'update'
  form.value = row
}

const updateForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      update(form.value).then(res => {
        if (res.code === 200) {
          dialogFormVisible.value = false
          ElMessage({
            message: "更新成功",
            type: 'success'
          })
        } else {
          ElMessage(res.msg)
        }
      }).catch(function (err) {
        console.log(err.message)
      })
    } else {
      return false;
    }
  });
}

const warnBeforeDelete = (idx, row) => {
  ElMessage.confirm(
    '确认删除当前执行器？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(response => {
    batchDelete(idx, row)
  }).catch(reject => console.log(reject))
}

const batchDelete = (idx, row) => {
  remove(row.id).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = executorList.value.indexOf(idx)
      executorList.value.splice(idx, 1)
      total.value--
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error',
        duration: 2000
      })
    }
  }).catch(function (err) {
    console.log(err.message)
  })
}

const formatAddressList = (addressList) => {
  if (addressList !== null && addressList !== '') {
    let addressArr = addressList.split(",")
    let showAddress = ''
    addressArr.forEach((val) => {
      showAddress += val + '<br>'
    })
    return showAddress
  }
  return "无"
}

const formatRegDesc = (type) => {
  switch(type) {
    case 0:
      return "自动注册"
    case 1:
      return ""
    default:
      return ""
  }
}

const handleFilter = () => {
  fetchTableData()
}

const handleSizeChange = (val) => {
  listQuery.value.length = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  listQuery.value.start = (val - 1) * listQuery.value.length
  fetchTableData()
}

const handleRefresh = () => {
  executorList.value = null
  total.value = null
  fetchTableData()
}

onMounted(() => {
  fetchTableData()
})
</script>

<style rel="stylesheet/scss" lang="scss" slot-scope>

  .app-container {
    padding: 20px;
  }

  .pagination-container {
    margin-top: 30px;
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .dialogModifyLessonManage {
    .el-dialog__header {
      padding-bottom: 0;
    }
    .el-dialog__body {
      padding: 0
    }
    .createPost-main-container {
      padding: 20px 0 !important;
    }
  }
</style>
